package cn.itcast.usermanage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.StreamingHttpOutputMessage.Body;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.tools.internal.ws.processor.model.Request;

import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@Controller
@RequestMapping("rest/user")
public class NewUserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="{id}" ,method=RequestMethod.GET)
	public ResponseEntity<User> queryById(@PathVariable("id")Long id){
		try {
			if(id==null||id.longValue()<=0){
				//400
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			int i=1/0;
			User user = this.userService.queryUserById(id);
			if(user==null){
				//404
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(user);
			}
			//200
			return ResponseEntity.status(HttpStatus.OK).body(user);
			//return ResponseEntity.ok(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}	
	
	@PostMapping
	public ResponseEntity<Void> insertUser(User user){
		try {
			if(user==null||StringUtils.isEmpty(user.getUserName())){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			Boolean b = this.userService.insertUser(user);
			if(b){
				return ResponseEntity.status(HttpStatus.CREATED).build();
			}
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	@PutMapping
	public ResponseEntity<Void> updateUser(User user){
		try {
			if(user==null||user.getId()==null||user.getId().longValue()<=0){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			Boolean b = this.userService.updateUser(user);
			if(b){
				return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
			}
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
}



